import { defineStore } from "pinia"
import http from "@/utils/http/http.js"
import { useUserStore } from "./user"

export const useAddressStore = defineStore("address", {
  state: () => ({
    addresses: [],
    currentAddress: null,
    defaultAddress: null,
    loading: false,
    error: null,
  }),

  getters: {
    // 获取地址列表
    addressList: (state) => state.addresses,

    // 获取默认地址
    getDefaultAddress: (state) => {
      if (state.defaultAddress) return state.defaultAddress
      return state.addresses.find((address) => address.isDefault === 1) || null
    },

    // 是否有地址
    hasAddress: (state) => state.addresses.length > 0,
  },

  actions: {
    // 获取地址列表
    async fetchAddresses() {
      this.loading = true
      this.error = null

      try {
        const userStore = useUserStore()
        const isLoggedIn = userStore.isLoggedIn
        const token = userStore.token

        if (!isLoggedIn || !token) {
          throw new Error("用户未登录")
        }

        const response = await http.get("/api/address/list", {
          header: {
            Authorization: `Bearer ${token}`,
          },
        })

        if (response.code === 200) {
          this.addresses = response.data || []
          return this.addresses
        } else {
          throw new Error(response.message || "获取地址列表失败")
        }
      } catch (error) {
        this.error = error.message || "获取地址列表失败"
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取默认地址
    async fetchDefaultAddress() {
      this.loading = true
      this.error = null

      try {
        const userStore = useUserStore()
        const isLoggedIn = userStore.isLoggedIn
        const token = userStore.token

        if (!isLoggedIn || !token) {
          throw new Error("用户未登录")
        }

        const response = await http.get("/api/address/default", {
          header: {
            Authorization: `Bearer ${token}`,
          },
        })

        if (response.code === 200) {
          this.defaultAddress = response.data
          return this.defaultAddress
        } else if (response.code === 200 && !response.data) {
          // 没有默认地址，但请求成功
          this.defaultAddress = null
          return null
        } else {
          throw new Error(response.message || "获取默认地址失败")
        }
      } catch (error) {
        this.error = error.message || "获取默认地址失败"
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取地址详情
    async fetchAddressDetail(id) {
      this.loading = true
      this.error = null

      try {
        const userStore = useUserStore()
        const isLoggedIn = userStore.isLoggedIn
        const token = userStore.token

        if (!isLoggedIn || !token) {
          throw new Error("用户未登录")
        }

        const response = await http.get(`/api/address/${id}`, {
          header: {
            Authorization: `Bearer ${token}`,
          },
        })

        if (response.code === 200) {
          this.currentAddress = response.data
          return this.currentAddress
        } else {
          throw new Error(response.message || "获取地址详情失败")
        }
      } catch (error) {
        this.error = error.message || "获取地址详情失败"
        throw error
      } finally {
        this.loading = false
      }
    },

    // 添加地址
    async addAddress(addressData) {
      this.loading = true
      this.error = null

      try {
        const userStore = useUserStore()
        const isLoggedIn = userStore.isLoggedIn
        const token = userStore.token

        if (!isLoggedIn || !token) {
          throw new Error("用户未登录")
        }

        const response = await http.post("/api/address/add", addressData, {
          header: {
            Authorization: `Bearer ${token}`,
          },
        })

        if (response.code === 200) {
          // 如果添加的是默认地址，更新默认地址
          if (addressData.isDefault === 1) {
            this.defaultAddress = response.data
          }

          // 刷新地址列表
          await this.fetchAddresses()

          return response.data
        } else {
          throw new Error(response.message || "添加地址失败")
        }
      } catch (error) {
        this.error = error.message || "添加地址失败"
        throw error
      } finally {
        this.loading = false
      }
    },

    // 更新地址
    async updateAddress(id, addressData) {
      this.loading = true
      this.error = null

      try {
        const userStore = useUserStore()
        const isLoggedIn = userStore.isLoggedIn
        const token = userStore.token

        if (!isLoggedIn || !token) {
          throw new Error("用户未登录")
        }

        const response = await http.put(`/api/address/${id}`, addressData, {
          header: {
            Authorization: `Bearer ${token}`,
          },
        })

        if (response.code === 200) {
          // 如果更新的是默认地址，更新默认地址
          if (addressData.isDefault === 1) {
            this.defaultAddress = response.data
          } else if (this.defaultAddress && this.defaultAddress.id === id) {
            // 如果原来是默认地址，但现在不是了，清空默认地址
            this.defaultAddress = null
          }

          // 刷新地址列表
          await this.fetchAddresses()

          return response.data
        } else {
          throw new Error(response.message || "更新地址失败")
        }
      } catch (error) {
        this.error = error.message || "更新地址失败"
        throw error
      } finally {
        this.loading = false
      }
    },

    // 删除地址
    async deleteAddress(id) {
      this.loading = true
      this.error = null

      try {
        const userStore = useUserStore()
        const isLoggedIn = userStore.isLoggedIn
        const token = userStore.token

        if (!isLoggedIn || !token) {
          throw new Error("用户未登录")
        }

        const response = await http.delete(`/api/address/${id}`, {
          header: {
            Authorization: `Bearer ${token}`,
          },
        })

        if (response.code === 200) {
          // 如果删除的是默认地址，清空默认地址
          if (this.defaultAddress && this.defaultAddress.id === id) {
            this.defaultAddress = null
          }

          // 从列表中移除
          this.addresses = this.addresses.filter((address) => address.id !== id)

          return true
        } else {
          throw new Error(response.message || "删除地址失败")
        }
      } catch (error) {
        this.error = error.message || "删除地址失败"
        throw error
      } finally {
        this.loading = false
      }
    },

    // 设置默认地址
    async setDefaultAddress(id) {
      this.loading = true
      this.error = null

      try {
        const userStore = useUserStore()
        const isLoggedIn = userStore.isLoggedIn
        const token = userStore.token

        if (!isLoggedIn || !token) {
          throw new Error("用户未登录")
        }

        const response = await http.post(
          `/api/address/set-default/${id}`,
          {},
          {
            header: {
              Authorization: `Bearer ${token}`,
            },
          },
        )

        if (response.code === 200) {
          // 更新本地地址列表中的默认状态
          this.addresses = this.addresses.map((address) => ({
            ...address,
            isDefault: address.id === id ? 1 : 0,
          }))

          // 更新默认地址
          const newDefault = this.addresses.find((address) => address.id === id)
          if (newDefault) {
            this.defaultAddress = newDefault
          }

          return true
        } else {
          throw new Error(response.message || "设置默认地址失败")
        }
      } catch (error) {
        this.error = error.message || "设置默认地址失败"
        throw error
      } finally {
        this.loading = false
      }
    },
  },
})
